package com.daigou.tools;

import java.io.File;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

/**
 * 
 * @description：文件上传通用处理工具类
 * @author lz
 * @version 创建时间：2017年01月19日  上午11:19:57
 */
public class UploadFileUtils {
	
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadFileUtils.class);
	
	private UploadFileUtils() {
	}
	
	/**
	 * 上传文件存放服务器
	 * @param request
	 * @param dir
	 * @return
	 */
	public static String getServerSaveDir(HttpServletRequest request, String dir){
		StringBuilder uploadPath = new StringBuilder(request.getSession().getServletContext().getRealPath("/upload"));
		uploadPath.append(File.separator);
		uploadPath.append(dir);
		uploadPath.append(File.separator);
		uploadPath.append(DateUtil.format(new Date(), "yyyyMMdd"));
		File file = new File(uploadPath.toString());
		if ( !file.exists() ) {
			file.mkdirs();
		}
		return file.getPath();
	}
	
	/**
	 * 文件重命名
	 * @param file
	 * @return
	 */
	public static String rename(MultipartFile file) {
		//获取原始文件名  
		String fileName = file.getOriginalFilename();
		//新文件名称，不设置时默认为原文件名
		return new Date().getTime()+(new Random().nextInt(9999-1000+1)+1000)+fileName.substring(fileName.lastIndexOf('.'));
	} 
	
	/**
	 * 文件保存路径
	 * @param request 
	 * @param serverSaveDir
	 * @param newFileName
	 * @return
	 */
	public static String getSavaDir(HttpServletRequest request,String serverSaveDir, String newFileName){
		StringBuilder savaPath = new StringBuilder();
		//文件存放路径
		savaPath.append(serverSaveDir);
		savaPath.append(File.separator);
		//文件名称
		savaPath.append(newFileName);
		
		//将绝对路径"\"替换成"/"
		String savaFilePath = savaPath.toString().replaceAll("\\\\", "/");
		//查询"/monkey"最后一个字母的位置
		String projectName = request.getSession().getServletContext().getContextPath().toLowerCase();
		int index =savaFilePath.toLowerCase().lastIndexOf(projectName)+request.getSession().getServletContext().getContextPath().length();
		//文件保存路径
		return savaFilePath.substring(index+1,savaFilePath.length());
	}
	
	/**
	 * 文件上传
	 * @param request
	 * @param imageFile
	 * @param imagePathPrifix
	 * @return
	 */
    public static String upload(HttpServletRequest request, MultipartFile imageFile, String imagePathPrifix) throws Exception{
    	//获取服务器的实际路径
    	String serverSaveDir = getServerSaveDir(request, imagePathPrifix);
    	//生成文件名称
    	String newFileName = rename(imageFile);
        String savePath = null;
        try{
        	savePath = serverSaveDir+File.separator+newFileName.toLowerCase();
            imageFile.transferTo(new File(savePath));  
        }catch(Exception e){
        	LOGGER.error("UploadFileUtils.Upload:{}", e);
        	throw e;
        }
		return savePath.substring(savePath.indexOf("upload"));
    }
}
